import os
import requests
from dotenv import load_dotenv
from requests.exceptions import RequestException

from logs import SingletonLogger

# URL для авторизации
load_dotenv()
BASE_URL = os.getenv('BASE_URL')
BEARER_TOKEN = os.getenv('BEARER_TOKEN')

logger = SingletonLogger.get_instance(__name__).get_logger()


class API:
    def __init__(self):
        self.base_url = BASE_URL
        self.token = BEARER_TOKEN
        self.headers = {'Authorization': f'Bearer {self.token}'}

    def get(self, endpoint):
        try:
            response = requests.get(f'{self.base_url}/{endpoint}', headers=self.headers)
            response.raise_for_status()
            logger.info(f'[GET] | /{endpoint} was successful')
            return response.json()
        except RequestException as e:
            logger.error(f'[GET] | /{endpoint} failed: {e}')
            return None

    def post(self, endpoint, data):
        try:
            response = requests.post(f'{self.base_url}/{endpoint}', headers=self.headers, json=data)
            response.raise_for_status()
            logger.info(f'[GET] | /{endpoint} was successful')
            return response.json()
        except RequestException as e:
            logger.error(f'[GET] | /{endpoint} failed: {e}')
            return None

    def put(self, endpoint, data):
        try:
            response = requests.put(f'{self.base_url}/{endpoint}', headers=self.headers, json=data)
            response.raise_for_status()
            logger.info(f'[GET] | /{endpoint} was successful')
            return response.json()
        except RequestException as e:
            logger.error(f'[GET] | /{endpoint} failed: {e}')
            return None

    def delete(self, endpoint):
        try:
            response = requests.delete(f'{self.base_url}/{endpoint}', headers=self.headers)
            response.raise_for_status()
            logger.info(f'[GET] | /{endpoint} was successful')
            return response.json()
        except RequestException as e:
            logger.error(f'[GET] | /{endpoint} failed: {e}')
            return None
